package com.skwyb.form.utils;

import lombok.extern.log4j.Log4j2;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

@Log4j2
public class DomainValidatorUtils {

    //获取validator对象
    private static Validator validator1=
            Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();
    private static Validator validator2=
            Validation.byProvider(HibernateValidator.class).configure().failFast(false).buildValidatorFactory().getValidator();

    public static <T> Set<ConstraintViolation<T>> validateFast(T domain) throws Exception {
        Set<ConstraintViolation<T>> validateResult= validator1.validate(domain);
        if(validateResult.size()>0) {
            log.error(validateResult.iterator().next().getMessage()+",校验失败");
        }

        return validateResult;
    }

    public static <T> Set<ConstraintViolation<T>> validateAll(T domain) {
        Set<ConstraintViolation<T>> validateResult= validator2.validate(domain);
        if(validateResult.size()>0) {
            for (ConstraintViolation<T> aValidateResult : validateResult) {
                log.error(aValidateResult.getMessage() + ",校验失败");
            }
        }

        return validateResult;
    }
}
